package demo.websocket;

import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
import org.junit.Test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;

public class WebSocketServerDemo {


    /**
     * 使用Java原生代码实现websocket服务的方法, 此方法需要引入一个第三方库java-websocket.jar.
     * <p>
     * 测试：此时web socket server已经监听在了localhost:8887上. 我们可以使用websocket在线调试工具对其进行测试.
     * http://coolaf.com/tool/chattest
     * 该工具主要是利用html5 的websocket去连接服务端的websocket,因此无论你是内网还是外网都可使用!
     * 打开工具在输入框中输入 ws://localhost:8887点击连接, 既可以看到服务器端的反馈, 同时web socket server的控制台也会输出日志信息.
     *
     * @throws InterruptedException
     * @throws IOException
     */
    @Test
    public void testWebSocketServer() throws InterruptedException, IOException {
        int port = 8887; // 843 flash policy port
        InetSocketAddress inetSocketAddress = new InetSocketAddress(port);
        WebSocketServer webSocketServer = new WebSocketServer(inetSocketAddress) {
            @Override
            public void onOpen(WebSocket conn, ClientHandshake handshake) {
                // This method sends a message to the new client
                conn.send("Welcome to the server!");
                // This method sends a message to all clients connected
                broadcast("new connection: " + handshake.getResourceDescriptor());
                String hostAddress = conn.getRemoteSocketAddress().getAddress().getHostAddress();
                System.out.println(hostAddress + " entered the room!");
            }

            @Override
            public void onClose(WebSocket conn, int code, String reason, boolean remote) {
                broadcast(conn + " has left the room!");
                System.out.println(conn + " has left the room!");

            }

            @Override
            public void onMessage(WebSocket conn, String message) {
                broadcast(message);
                System.out.println(conn + ": " + message);
            }

            @Override
            public void onError(WebSocket conn, Exception ex) {
                ex.printStackTrace();
                if (conn != null) {
                    // some errors like port binding failed may not be assignable to a specific
                    // websocket
                }

            }

            @Override
            public void onStart() {
                System.out.println("Server started!");
                setConnectionLostTimeout(0);
                setConnectionLostTimeout(100);

            }
        };
        webSocketServer.start();

        System.out.println("ChatServer started on port: " + webSocketServer.getPort());

        BufferedReader sysin = new BufferedReader(new InputStreamReader(System.in));
        while (true) {
            String in = sysin.readLine();
            webSocketServer.broadcast(in);
            if (in.equals("exit")) {
                webSocketServer.stop(1000);
                break;
            }
        }
    }


}
